# coding: utf-8

from vec2 import vec2
from typing import Sequence, cast
from graph import EdgeAttr, NodeAttr
from layout import SugiyamaLayout
import math
from .DrawingOptions import DrawingOptions
from .SvgImage import SvgImage


def adjust_points_for_circles(points: Sequence[vec2], radius: float):
    if len(points) < 2:
        return points  # 如果点少于两个，直接返回原始列表

    adjusted_points = []
    n = len(points)
    for i in range(n - 1):
        start = points[i]
        end = points[i + 1]
        dx = end.x - start.x
        dy = end.y - start.y
        distance = math.sqrt(dx**2 + dy**2)
        if distance == 0:  # 避免除以0
            continue  # 相同的点不做处理，继续下一个点
        ux, uy = dx / distance, dy / distance
        if i == 0:  # 处理第一个点
            adjusted_start = vec2(start.x + ux * radius, start.y + uy * radius)
            adjusted_points.append(adjusted_start)
        if i < n - 2:  # 处理中间点到下一个点的圆心
            adjusted_points.append(end)
        else:  # 处理倒数第二个点到最后一个点的边缘
            adjusted_end = vec2(end.x - ux * radius, end.y - uy * radius)
            adjusted_points.append(adjusted_end)

    return adjusted_points


# -------------------------------------------------------------------------------------------------


def draw_edge(img: SvgImage, p: EdgeAttr, opts: DrawingOptions, arrow_size: float):
    # get the color
    color = opts.edge_colors.get((p.u, p.v), "black")
    print("绘制分支:", p.u, p.v, " ".join([str(p) for p in p.points]))

    # draw the lines
    img.draw_polyline(p.points, color)
    # HACK 张志龙的改动
    # radius = 15  # 这里要跟随图内节点的半径
    # adjusted_points = adjust_points_for_circles(p.points, radius)
    # img.draw_polyline(adjusted_points, color)

    # ---------------------------------------------------------------------------------------------
    # print('p.points',[f"{p.x},{p.y}" for p in p.points])
    # print('=-=-=-=-=-===========', p.points[-2], p.points[-1])
    # draw the arrow
    # TODO
    # p.points = [p if p is not None else vec2() for p in p.points]

    img.draw_arrow(p.points[-2], p.points[-1], arrow_size, color)
    if p.bidirectional:
        img.draw_arrow(p.points[1], p.points[0], arrow_size, color)


def draw_svg_image(layout: SugiyamaLayout, opts: DrawingOptions, filename: str):
    img = SvgImage(layout.dimensions(), opts.margin)

    for o in layout.vertices():
        node = cast(NodeAttr, o)
        label = opts.labels.get(node.u, str(node.u))
        color = opts.colors.get(node.u, "black")
        try:
            if int(label) > 155:
                continue  # HACK 跳过特殊节点的当前循环迭代
        except ValueError:
            pass  # label 不是数字，继续绘制

        # print('绘制节点:', node.u, node.pos)
        img.draw_circle(node.pos, layout.attribs().node_size, color)
        img.draw_text(node.pos, label, opts.font_size, color)

    arrow_size = 1 * layout.attribs().node_size
    for path in layout.edges():
        # print('ccccccccccccccccccc', path)
        draw_edge(img, path, opts, arrow_size)
    # 保存svg文件
    img.save(filename)
